package com.ineatconseil.yougo.components;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ineatconseil.yougo.dto.UserTypeDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.services.rest.RestPath;
import com.ineatconseil.yougo.services.rest.RestServiceInvoker;

/**
 * Component use to convert the user type.
 * 
 * @author johanblo
 * 
 */
public class UserTypeLabel {

	private static Map<Long, UserTypeDto> types = new HashMap<Long, UserTypeDto>();

	@Inject
	private RestServiceInvoker restServiceInvoker;

	@Parameter
	private long value = 0;

	@BeginRender
	void renderMessage(MarkupWriter writer) {

		try {

			if (value != 0) {

				if (!types.containsKey(value)) {
					types.put(value, getUserType());
				}

				UserTypeDto userType = types.get(value);
				if (userType != null) {
					writer.write(userType.getDescription());
				}

			}

		} catch (RestServiceException e) {
			writer.write("");
		}

	}

	private UserTypeDto getUserType() throws RestServiceException {

		List<RestPath> paths = new ArrayList<RestPath>();
		paths.add(new RestPath("user-types", String.valueOf(value)));

		return restServiceInvoker.call(paths, UserTypeDto.class);

	}

}